<template>
  <view class="root">
    <view class="top">
      <view class="inner">
        <view class="top-title">
          请上传有效身份证件的正反面
        </view>

        <view class="front-view view-item">
          <view class="i-left">
            <view class="b-title">正面</view>
            <view class="tip-name">请上传有姓名头像的一面</view>
          </view>
          <view class="i-right">
            <u-upload :fileList="form.idCardImage" @afterRead="(info) => uploadFrontImage(info)"
              @delete="(info) => deletePhoto(info, 'form')" name="idCardImage" :maxCount="1" :multiple="true"
              width="235rpx" height="162rpx">
              <image v-if="form.idCardImage.length == 0" :src="baseImgUrl + 'idcard-front.png'" style="width: 235rpx; height: 162rpx;position: absolute;top
              50%; left: 50%; transform: translate(-50%, -50%);top: 50%;"></image>
            </u-upload>
          </view>
        </view>
        <view class="back-view view-item">
          <view class="i-left">
            <view class="b-title">反面</view>
            <view class="tip-name">请上传证件背面</view>
          </view>
          <view class="i-right">
            <u-upload :fileList="form.idCardImageBack" @afterRead="(info) =>  uploadBackImage(info)"
              @delete="(info) => deletePhoto(info, 'form')" name="idCardImageBack" :maxCount="1" :multiple="true"
              width="235rpx" height="162rpx">
              <image v-if="form.idCardImageBack.length == 0" :src="baseImgUrl + 'idcard-back.png'" style="width: 235rpx; height: 162rpx;position: absolute;top
              50%; left: 50%; transform: translate(-50%, -50%);top: 50%;"></image>
            </u-upload>
          </view>
        </view>
        <view class="tips-info">
          注意：我们郑重承诺，对于用户上传的证件信息，我们将严格遵守相关法律法规，确保这些信息仅用于身份验证等必要目的，绝不会被用于任何其他未经授权的用途，全力保障您的身份信息安全。
        </view>
      </view>
    </view>
    <view class="bottom">
      <u-button text="取消" :custom-style="halfCancelButton" @click="handleCancel"></u-button>
      <u-button text="保存" :custom-style="halfSaveButton" @click="handleSubmit"></u-button>
    </view>
  </view>
</template>

<script>
  import {
    Toast,
    getBase64Two,
    getOptionsParams,
    halfCancelButton,
    halfSaveButton,
    navBack
  } from '@/utils/util.js'
  import pickerMixin from '../../utils/picker-mixin';
  import uploadFileMixin from '../../utils/upload-file-mixin';
  export default {
    mixins: [pickerMixin, uploadFileMixin],
    data() {
      return {
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        baseImgUrl: this.$baseImgUrl,
        imgPrefix: uni.getStorageSync("imgPrefix"),
        halfCancelButton,
        halfSaveButton,
        form: this.initForm(),
        routerParams: {}
      }
    },
    onLoad(options) {
      this.routerParams = getOptionsParams(options)

      // 设置路径里面携带的参数
      if (this.routerParams.idCardImage) {
        this.form.idCardImage = [{
          url: this.imgPrefix + this.routerParams.idCardImage,
          halfPath: this.routerParams.idCardImage
        }]
      }

      if (this.routerParams.idCardImageBack) {
        this.form.idCardImageBack = [{
          url: this.imgPrefix + this.routerParams.idCardImageBack,
          halfPath: this.routerParams.idCardImageBack
        }]
      }

    },
    onUnload() {},
    methods: {
      initForm() {
        return {
          idCardImage: [],
          idCardImageBack: []
        }
      },
      handleCancel() {
        navBack()
      },
      handleSubmit() {
        // 判断是否上传身份证照片
        if (!this.form.idCardImage.length) {
          Toast('请上传证件照正面照片！')
          return
        }
        if (!this.form.idCardImageBack.length) {
          Toast('请上传证件照背面照片！')
          return
        }
        uni.$emit('saveIdPhoto', this.form)
        navBack()
      },
      identifyIdCard(fileInfo, idCardType = 'front') {
        return new Promise((resolve, reject) => {
          uni.request({
            url: "https://aip.baidubce.com/oauth/2.0/token",
            method: "GET",
            data: {
              grant_type: "client_credentials",
              client_id: this.clientId,
              client_secret: this.clientSecret,
            },
            success: (res) => {
              let token = res.data.access_token
              getBase64Two(fileInfo.file[0].url)
                .then((res) => {
                  return res;
                })
                .then((base64Str) => {
                  uni.request({
                    url: `https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=${token}`,
                    method: "POST",
                    header: {
                      "Content-Type": "application/x-www-form-urlencoded",
                    },
                    data: {
                      id_card_side: idCardType,
                      image: base64Str,
                      detect_direction: true,
                      detect_card: true
                    },
                    success: (resbai) => {
                      let {
                        statusCode,
                        data
                      } = resbai;

                      if (statusCode == 200) {
                        resolve(data)
                        // 识别成功之后再上传图片
                      } else {
                        reject("未识别出身份证信息，请重试！")
                        Toast("未识别出身份证信息，请重试！");
                      }
                    },
                  });
                })
            },
          });
        })
      },
      uploadFrontImage(info) {
        // 先校验图片
        if (this.routerParams.idType == 10) {
          this.identifyIdCard(info, 'front')
            .then((res) => {
              if (res.image_status == 'normal') {
                this.afterReadFive(info, 'form', 44)
              } else {
                Toast('上传图片不是身份证正面照，请检查！')
              }
            })
        } else {
          this.afterReadFive(info, 'form', 44)
        }
      },
      uploadBackImage(info) {
        // 先校验图片
        if (this.routerParams.idType == 10) {
          this.identifyIdCard(info, 'back')
            .then((res) => {
              if (res.image_status == 'normal') {
                this.afterReadFive(info, 'form', 44)
              } else {
                Toast('上传图片不是身份证反面照，请检查！')
              }
            })
        } else {
          this.afterReadFive(info, 'form', 44)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .root {
    width: 100%;
    height: 100%;
    background: #F9F9F9;
    display: flex;
    flex-direction: column;

    .top {
      flex: 1;
      margin: 14rpx 16rpx;
      min-height: 0;
      overflow: auto;
      background: #fff;
    }

    .bottom {
      height: 120rpx;
      background: #FFFFFF;
      border-radius: 0rpx 0rpx 0rpx 0rpx;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 24rpx;

      /deep/.u-button__text {
        font-weight: bold;
        font-size: 32rpx;
      }
    }

    .inner {
      width: 100%;
      display: flex;
      flex-direction: column;
      padding: 37rpx 32rpx;

      /deep/.u-upload__wrap__preview__image {
        margin-top: 21rpx;
        margin-left: 23rpx;
      }

      .top-title {
        font-weight: bold;
        font-size: 32rpx;
        color: #000000;
        line-height: 32rpx;
        padding-left: 8rpx;
        margin-bottom: 35rpx;
      }

      .view-item {
        display: flex;
        background: #F4F6F8;
        border-radius: 16rpx 16rpx 16rpx 16rpx;
        padding: 29rpx 23rpx;
        justify-content: space-between;

        .i-left {
          .b-title {
            font-weight: bold;
            font-size: 28rpx;
            color: #000000;
            margin-bottom: 18rpx;
          }

          .tip-name {
            font-weight: 500;
            font-size: 26rpx;
            color: #BFBFC7;
          }
        }

        .i-right {
          width: 281rpx;
          height: 204rpx;
          background: #E1EFFF;
          border-radius: 8rpx 8rpx 8rpx 8rpx;
          margin-left: 16rpx;
          position: relative;
        }
      }

      .back-view {
        margin-top: 32rpx;
      }

      .tips-info {
        font-weight: 500;
        font-size: 26rpx;
        color: #333333;
        line-height: 36rpx;
        margin-top: 46rpx;
      }
    }
  }
</style>